package org.simple_blogging; 

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;

@SuppressWarnings("serial")
public class BlogPreview extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html");
		resp.getWriter().println("ERROR 404: Page Not Found!!!");
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		
		String blogTitle = req.getParameter("blog_title");
		String blogText = req.getParameter("blog_text");
		
		String blogTitleEsc = StringEscapeUtils.escapeHtml(blogTitle);
		String blogTextEsc = StringEscapeUtils.escapeHtml(blogText);
		
		blogTextEsc = blogTextEsc.replaceAll("\r\n", "<br />");
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		Date currentDateTime = new Date();

		String datePosted = dateFormat.format(currentDateTime);
		
		String hiddenForm = "<form method=\"POST\" action=\"save_blog\">" +
							"<input type=\"hidden\" name=\"blog_title\" value=\"" + blogTitleEsc + "\"</input>" +
							"<input type=\"hidden\" name=\"blog_text\" value=\"" + blogTextEsc + "\"</input>" +
							"<input type=\"hidden\" name=\"date_submitted\" value=\"" + datePosted + "\"</input>" +
							"<input type=\"submit\" value=\"Confirm\" />" +
							"</form>";
		
		dateFormat.setTimeZone(TimeZone.getTimeZone("PST"));
		String dispDate = dateFormat.format(currentDateTime);
		
		out.print("<html>" +
				"<title> Blog Post Preview </title>" +
				"<body>" +
				"<b>" + blogTitleEsc + "</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
				"<i>Posted on: " + dispDate + "</i>" + 
				"<br /><br />" + blogTextEsc + "<br /><br />" +
				hiddenForm +
				"</body>" +
				"</html>");
		
	}
}
